# -*- coding: utf-8 -*-
# owner: shenyi

import asyncio
from src.models.instance import (
    CreateInstanceRequest,
    DeleteInstanceRequest,
    InstanceTypeRequest,
    QueryInstanceRequest,
    AvailableInstanceTypeRequest
)
from src.models.responses import (
    CreateResponse,
    DeleteResponse,
    InstanceTypeResponse,
    AvailableZonesInstanceTypeResponse,
    InstanceListResponse
)
from src.core import logger, config
from src.providers import get_provider
from src.constants import DEFAULT_PROVIDER_ENV_KEY

class InstanceService:
    """
    实例服务类，用于管理云服务器实例的创建、删除等操作
    """
    
    def __init__(self, provider: str = None):
        self.logger = logger()
        self.config = config()
        provider_type = provider or self.config.get(DEFAULT_PROVIDER_ENV_KEY, 'aliyun')  # 默认使用阿里云
        self.provider = get_provider(name=provider_type)
    
    async def create_instance(self, request: CreateInstanceRequest) -> CreateResponse:
        """
        创建云服务器实例
        
        :param request: 创建实例请求对象
        :return: 创建结果响应
        """
        try:
            self.logger.info(f"Creating instance with request: {request}")
            response = await self.provider.create_instance(request)
            self.logger.info(f"Instance created successfully")
            return response
        except Exception as e:
            self.logger.error(f"Failed to create instance: {str(e)}")
            raise
    
    async def delete_instance(self, request: DeleteInstanceRequest) -> DeleteResponse:
        """
        删除云服务器实例
        
        :param request: 删除实例请求对象
        :return: 删除结果响应
        """
        try:
            self.logger.info(f"Deleting instance: {request.instance_id} in region {request.region_id}")
            response = await self.provider.delete_instance(request)
            self.logger.info(f"Instance {request.instance_id} deleted successfully")
            return response
        except Exception as e:
            self.logger.error(f"Failed to delete instance {request.instance_id}: {str(e)}")
            raise
    
    async def list_instances(self, request: QueryInstanceRequest) -> InstanceListResponse:
        """
        查询云服务器实例列表
        
        :param request: 查询实例请求对象
        :return: 实例列表响应
        """
        try:
            self.logger.info(f"Listing instances with request: {request}")
            response = await self.provider.list_instances(request)
            self.logger.info(f"Retrieved {len(response.instances) if response.instances else 0} instances")
            return response
        except Exception as e:
            self.logger.error(f"Failed to list instances: {str(e)}")
            raise
    
    async def list_instance_types(self, request: InstanceTypeRequest) -> InstanceTypeResponse:
        """
        查询实例规格列表
        
        :param request: 实例规格查询请求
        :return: 实例规格响应
        """
        try:
            self.logger.info(f"Listing instance types in region: {request.region_id}")
            response = await self.provider.list_instance_types(request)
            return response
        except Exception as e:
            self.logger.error(f"Failed to list instance types: {str(e)}")
            raise
    
    async def list_available_instance_types(self, request: AvailableInstanceTypeRequest) -> AvailableZonesInstanceTypeResponse:
        """
        查询可用实例规格
        
        :param request: 可用实例规格查询请求
        :return: 可用区和实例类型响应
        """
        try:
            self.logger.info(f"Listing available instance types in zone: {request.zone_id}")
            response = await self.provider.list_available_instance_types(request)
            return response
        except Exception as e:
            self.logger.error(f"Failed to list available instance types: {str(e)}")
            raise
    
    async def health_check(self) -> bool:
        """
        健康检查
        
        :return: True表示健康，False表示异常
        """
        try:
            result = await self.provider.health_check()
            if result:
                self.logger.info("Cloud provider health check passed")
            else:
                self.logger.warning("Cloud provider health check failed")
            return result
        except Exception as e:
            self.logger.error(f"Health check error: {str(e)}")
            return False

# 使用示例
async def main():
    """
    使用示例
    """
    service = InstanceService()
    
    # 健康检查
    if await service.health_check():
        # 查询实例列表示例
        query_request = QueryInstanceRequest(
            region_id='cn-beijing'
        )
        
        try:
            response = await service.list_instances(query_request)
            print(f"Found {len(response.instances)} instances")
        except Exception as e:
            print(f"Failed to list instances: {e}")
    else:
        print("Cloud provider is not healthy")

if __name__ == "__main__":
    asyncio.run(main())